package com.tomecode.tools.maven.settings;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 
 * 
 * everything about local repository
 * 
 * 
 * @author Frastia Tomas
 * 
 */
public final class RepositoryFactory {

	private static final SAXReader reader = new SAXReader();
	private static final String E_PROJECT = "project";
	// private static final String E_PARENT = "parent";
	private static final String E_GROUP_ID = "groupId";

	public static final List<String> getPluginGroups(File repository) {
		return loadReapository2(repository, new ArrayList<String>());
	}

	public static final List<String> loadReapository2(File repository, List<String> list) {

		File[] files = repository.listFiles();
		for (File file : files) {
			if (file.isDirectory()) {
				List<String> groupIds = loadReapository2(file, list);
				merg(list, groupIds);
				continue;
			}
			if (file.isFile() && file.getName().endsWith(".pom")) {
				String groupId = loadGroupId(file);
				if (groupId == null || groupId.trim().length() == 0) {
					continue;
				}
				if (!list.contains(groupId)) {
					list.add(groupId);
				}
			}

		}

		return list;
	}

	/**
	 * load groupe id from pom.xml
	 * 
	 * @param file
	 * @return
	 */
	private static final String loadGroupId(File file) {
		try {
			Document document = reader.read(file);
			if (document == null) {
				return null;
			} else if (!document.getRootElement().getName().equals(E_PROJECT)) {
				return null;
			}

			Element element = document.getRootElement();
			return element.elementText(E_GROUP_ID);
		} catch (DocumentException e) {
			e.printStackTrace();
		}

		return null;
	}

	private static final void merg(List<String> list, List<String> groupIds) {
		for (String groupid : groupIds) {
			if (groupid == null || groupid.trim().length() == 0) {
				continue;
			}
			if (!list.contains(groupid)) {
				list.add(groupid);
			}
		}
	}

}
